﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.LIB;
using YArchitech.Revit.Electric.Common;

namespace YArchitech.Revit.MEP.Calculator
{
	public partial class DlgCreateRoomTag : System.Windows.Forms.Form
	{
		public DlgCreateRoomTag()
		{
			this.InitializeComponent();
		}

		public DlgCreateRoomTag(ExternalCommandData cmmandData)
		{
			this.InitializeComponent();
			this.btnAdd.Image = Resource.GetImage("AddNew16");
			this.btnModify.Image = Resource.GetImage("modify16");
			this.btnDelete.Image = Resource.GetImage("delete16");
			this.commData = cmmandData;
			this.m_doc = this.commData.Application.ActiveUIDocument.Document;
			this.SetToolTip();
			this.m_lstSelLevels = DlgBuildingFloors.GetSortLevels(this.m_doc, double.MinValue, double.MaxValue);
		}

		private void DlgCreateRoomTag_Load(object sender, EventArgs e)
		{
			base.Icon = Resource.YArchitechIcon;
			this.xmlInfo = new XmlInfo();
			DlgCreateRoomTag.listRoomType = this.xmlInfo.LoadRoomTypeData();
			this.DataBind();
		}

		private void DataBind()
		{
			BindingSource bindingSource = new BindingSource();
			bindingSource.DataSource = DlgCreateRoomTag.listRoomType;
			bindingSource.ResetBindings(true);
			this.dgvRoomKeyInfo.DataSource = bindingSource;
		}

		private void SetToolTip()
		{
			this.dgvRoomKeyInfo.ShowCellToolTips = false;
			this.toolTip1.AutomaticDelay = 0;
			this.toolTip1.OwnerDraw = true;
			this.toolTip1.ShowAlways = true;
			this.toolTip1.ToolTipTitle = "Custom Tooltip: ";
			this.toolTip1.UseAnimation = false;
			this.toolTip1.UseFading = false;
		}

		private void toolTip1_Draw(object sender, DrawToolTipEventArgs e)
		{
			e.Graphics.FillRectangle(Brushes.AliceBlue, e.Bounds);
			e.Graphics.DrawRectangle(Pens.White, new System.Drawing.Rectangle(0, 0, e.Bounds.Width - 1, e.Bounds.Height - 1));
			e.Graphics.DrawString(e.ToolTipText, e.Font, Brushes.Black, e.Bounds);
		}

		private void dgvRoomKeyInfo_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
		{
			this.toolTip1.Hide(this.dgvRoomKeyInfo);
		}

		private void dgvRoomKeyInfo_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
		{
			DataGridView dataGridView = (DataGridView)sender;
			if (dataGridView.Columns[e.ColumnIndex].Name == "TypeName" || e.RowIndex < 0 || e.RowIndex >= dataGridView.Rows.Count)
			{
				e.Cancel = true;
			}
		}

		private void dgvRoomKeyInfo_CellEndEdit(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex < 0 || e.RowIndex >= this.dgvRoomKeyInfo.Rows.Count)
			{
				return;
			}
			if (this.dgvRoomKeyInfo.Rows[e.RowIndex].Cells["KeyName"].Value == null)
			{
				return;
			}
			if (string.IsNullOrEmpty(this.dgvRoomKeyInfo.Rows[e.RowIndex].Cells["KeyName"].Value.ToString()))
			{
				this.dgvRoomKeyInfo.Rows[e.RowIndex].Cells["KeyName"].Selected = true;
				return;
			}
			string b = this.dgvRoomKeyInfo.Rows[e.RowIndex].Cells["KID"].Value.ToString();
			foreach (RoomType roomType in DlgCreateRoomTag.listRoomType)
			{
				if (roomType.KID == b)
				{
					roomType.KeyName = Convert.ToString(this.dgvRoomKeyInfo.Rows[e.RowIndex].Cells["KeyName"].Value);
					roomType.TypeName = Convert.ToString(this.dgvRoomKeyInfo.Rows[e.RowIndex].Cells["TypeName"].Value);
				}
			}
		}

		private void dgvRoomKeyInfo_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
		{
			if (e.RowIndex >= this.dgvRoomKeyInfo.Rows.Count)
			{
				return;
			}
			if (this.dgvRoomKeyInfo.Rows[e.RowIndex].Cells["TypeName"].ColumnIndex == e.ColumnIndex || e.RowIndex < 0)
			{
				return;
			}
			if (this.dgvRoomKeyInfo.Columns[e.ColumnIndex].Name == "KeyName" && e.RowIndex >= 0)
			{
				if (e.FormattedValue == null || string.IsNullOrEmpty(e.FormattedValue.ToString()))
				{
					MessageBox.Show("关键字不能为空。", "盈建科提示");
					e.Cancel = true;
				}
				foreach (object obj in ((IEnumerable)this.dgvRoomKeyInfo.Rows))
				{
					DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
					string[] array = e.FormattedValue.ToString().Split(new char[]
					{
						',',
						'，'
					});
					if (dataGridViewRow.Index != e.RowIndex && dataGridViewRow.Cells[e.ColumnIndex].Value != null)
					{
						foreach (string b in dataGridViewRow.Cells[e.ColumnIndex].Value.ToString().Split(new char[]
						{
							',',
							'，'
						}))
						{
							string[] array3 = array;
							for (int j = 0; j < array3.Length; j++)
							{
								if (array3[j] == b)
								{
									MessageBox.Show("关键字不能重复。", "盈建科提示");
									e.Cancel = true;
									return;
								}
							}
						}
					}
				}
			}
		}

		private void dgvRoomKeyInfo_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			if (this.dgvRoomKeyInfo.Columns[e.ColumnIndex].Name == "TypeName" && e.RowIndex >= 0 && e.RowIndex < this.dgvRoomKeyInfo.Rows.Count)
			{
				string text = this.dgvRoomKeyInfo.SelectedRows[0].Cells["TypeName"].Value.ToString();
				string id = this.dgvRoomKeyInfo.SelectedRows[0].Cells["TypeID"].Value.ToString();
				string[] array = text.Split(new char[]
				{
					'-'
				});
				using (DlgRoomTypeManage dlgRoomTypeManage = new DlgRoomTypeManage(array[0], array[1], array[2], id))
				{
					if (dlgRoomTypeManage.ShowDialog() == DialogResult.OK)
					{
						this.dgvRoomKeyInfo.SelectedRows[0].Cells["TypeName"].Value = string.Concat(new string[]
						{
							dlgRoomTypeManage.RoomTypeData.Industry,
							"-",
							dlgRoomTypeManage.RoomTypeData.BuildingType,
							"-",
							dlgRoomTypeManage.RoomTypeData.Place
						});
						this.dgvRoomKeyInfo.SelectedRows[0].Cells["TypeID"].Value = dlgRoomTypeManage.RoomTypeData.Id;
					}
				}
			}
		}

		private void btnAdd_Click(object sender, EventArgs e)
		{
			if (this.dgvRoomKeyInfo.SelectedRows.Count == 0)
			{
				RoomType backupRoomTypeDefaultData = this.xmlInfo.GetBackupRoomTypeDefaultData();
				DlgCreateRoomTag.listRoomType.Add(backupRoomTypeDefaultData);
				this.DataBind();
				return;
			}
			this.dgvRoomKeyInfo.Columns["KeyName"].ReadOnly = false;
			this.dgvRoomKeyInfo.Columns["TypeName"].ReadOnly = false;
			List<int> list = new List<int>();
			bool flag = false;
			foreach (object obj in ((IEnumerable)this.dgvRoomKeyInfo.Rows))
			{
				DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
				if (Convert.ToString(dataGridViewRow.Cells["KeyName"].Value).Contains("新房间"))
				{
					string value = Convert.ToString(dataGridViewRow.Cells["KeyName"].Value).Substring(3);
					try
					{
						list.Add(Convert.ToInt32(value));
					}
					catch (Exception)
					{
					}
				}
				if (Convert.ToString(dataGridViewRow.Cells["KeyName"].Value) == "新房间")
				{
					flag = true;
				}
			}
			RoomType roomType = new RoomType();
			roomType.KID = Guid.NewGuid().ToString().ToUpper();
			if (list.Count != 0)
			{
				roomType.KeyName = "新房间" + (list.Max<int>() + 1);
			}
			else if (flag)
			{
				roomType.KeyName = "新房间" + 1;
			}
			else
			{
				roomType.KeyName = "新房间";
			}
			roomType.TypeName = Convert.ToString(this.dgvRoomKeyInfo.SelectedRows[0].Cells["TypeName"].Value);
			roomType.TypeID = Convert.ToString(this.dgvRoomKeyInfo.SelectedRows[0].Cells["TypeID"].Value);
			DlgCreateRoomTag.listRoomType.Add(roomType);
			this.DataBind();
			int num = 0;
			foreach (object obj2 in ((IEnumerable)this.dgvRoomKeyInfo.Rows))
			{
				DataGridViewRow dataGridViewRow2 = (DataGridViewRow)obj2;
				if (Convert.ToString(dataGridViewRow2.Cells["KID"].Value) == DlgCreateRoomTag.listRoomType.Last<RoomType>().KID)
				{
					num = dataGridViewRow2.Index;
				}
			}
			this.dgvRoomKeyInfo.ClearSelection();
			this.dgvRoomKeyInfo.Rows[num].Selected = true;
			this.dgvRoomKeyInfo.Rows[num].Visible = true;
			this.dgvRoomKeyInfo.FirstDisplayedScrollingRowIndex = num;
			this.dgvRoomKeyInfo.CurrentCell = this.dgvRoomKeyInfo.Rows[num].Cells["KeyName"];
			this.dgvRoomKeyInfo.BeginEdit(true);
		}

		private void btnModify_Click(object sender, EventArgs e)
		{
			if (this.dgvRoomKeyInfo.SelectedRows.Count > 0)
			{
				this.dgvRoomKeyInfo.Columns["KeyName"].ReadOnly = false;
				this.dgvRoomKeyInfo.Columns["TypeName"].ReadOnly = false;
				this.dgvRoomKeyInfo.CurrentCell = this.dgvRoomKeyInfo.SelectedRows[0].Cells["KeyName"];
				this.dgvRoomKeyInfo.BeginEdit(true);
			}
		}

		private void btnDelete_Click(object sender, EventArgs e)
		{
			if (this.dgvRoomKeyInfo.SelectedRows.Count > 0 && MessageBox.Show("确定要删除此信息？", "盈建科提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
			{
				int index = this.dgvRoomKeyInfo.SelectedRows[0].Index;
				RoomType roomType = new RoomType();
				roomType.KID = Convert.ToString(this.dgvRoomKeyInfo.SelectedRows[0].Cells["Kid"].Value);
				roomType.KeyName = Convert.ToString(this.dgvRoomKeyInfo.SelectedRows[0].Cells["KeyName"].Value);
				roomType.TypeName = Convert.ToString(this.dgvRoomKeyInfo.SelectedRows[0].Cells["TypeName"].Value);
				roomType.TypeID = Convert.ToString(this.dgvRoomKeyInfo.SelectedRows[0].Cells["TypeID"].Value);
				RoomType item = new RoomType();
				foreach (RoomType roomType2 in DlgCreateRoomTag.listRoomType)
				{
					if (roomType2.KID == roomType.KID)
					{
						item = roomType2;
						break;
					}
				}
				DlgCreateRoomTag.listRoomType.Remove(item);
				this.DataBind();
				if (this.dgvRoomKeyInfo.Rows.Count > 0 && this.dgvRoomKeyInfo.Rows.Count != 1)
				{
					if (this.dgvRoomKeyInfo.Rows.Count == index)
					{
						this.dgvRoomKeyInfo.Rows[this.dgvRoomKeyInfo.Rows.Count - 1].Selected = true;
						return;
					}
					this.dgvRoomKeyInfo.Rows[index].Selected = true;
				}
			}
		}

		private void btnCancle_Click(object sender, EventArgs e)
		{
			base.Close();
		}

		private void btnOK_Click(object sender, EventArgs e)
		{
			this.xmlInfo.SaveSpaceKeyword(DlgCreateRoomTag.listRoomType);
		}

		private void btnAdd_MouseEnter(object sender, EventArgs e)
		{
			this.tipBtn.SetToolTip(this.btnAdd, "添加");
		}

		private void btnModify_MouseEnter(object sender, EventArgs e)
		{
			this.tipBtn.SetToolTip(this.btnModify, "修改");
		}

		private void btnDelete_MouseEnter(object sender, EventArgs e)
		{
			this.tipBtn.SetToolTip(this.btnDelete, "删除");
		}

		public static string GetRoomLightingTag(Autodesk.Revit.DB.Document doc)
		{
			return Path.Combine(Product.FamilyLocation, RevitVersion.GetVersionNumber(doc), "ElectricMark") + "\\";
		}

		public static string GetName(string fullName)
		{
			int num = fullName.LastIndexOf("\\");
			int num2 = fullName.LastIndexOf(".");
			return fullName.Substring(num + 1, num2 - num - 1);
		}

		public static bool GetLoadFamly(Autodesk.Revit.DB.Document doc, string familyPath)
		{
			string name = DlgCreateRoomTag.GetName(familyPath);
			Transaction transaction = new Transaction(doc, "LoadFamily");
			transaction.Start();
			try
			{
				familyPath = DlgCreateRoomTag.GetRoomLightingTag(doc) + name + ".rfa";
				bool result = doc.LoadFamily(familyPath);
				transaction.Commit();
				return result;
			}
			catch (Exception)
			{
				transaction.RollBack();
			}
			return false;
		}

		private static FamilySymbol GetConduitFittings(Autodesk.Revit.DB.Document doc, string fittingName)
		{
			string fn = DlgCreateRoomTag.GetName(fittingName);
			List<FamilySymbol> list = (from r in (from ele in RevitFilter.GetElementsOfType(doc, typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_GenericAnnotation)
			select (FamilySymbol)ele).ToList<FamilySymbol>()
			where r.Family.Name == fn
			select r).ToList<FamilySymbol>();
			if (list.Count == 0 && DlgCreateRoomTag.GetLoadFamly(doc, fittingName))
			{
				list = (from r in (from ele in RevitFilter.GetElementsOfType(doc, typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_GenericAnnotation)
				select (FamilySymbol)ele).ToList<FamilySymbol>()
				where r.Family.Name == fn
				select r).ToList<FamilySymbol>();
			}
			if (list.Count > 0)
			{
				return list[0];
			}
			return null;
		}

		private void btnSure_Click(object sender, EventArgs e)
		{
			if (this.m_lstSelLevels.Count <= 0)
			{
				YJKMessageBox.Show("没有选择楼层");
				return;
			}
			AnnotationSymbolType annotationSymbolType = null;
			Family family = null;
			if (family == null)
			{
				string fittingName = Path.Combine(DlgCreateRoomTag.GetRoomLightingTag(this.m_doc), "房间照明标记.rfa");
				annotationSymbolType = (DlgCreateRoomTag.GetConduitFittings(this.m_doc, fittingName) as AnnotationSymbolType);
			}
			if (family == null && annotationSymbolType == null)
			{
				MessageBox.Show("载入\"房间照明标记\"族失败,请检查族库中是否包含该族。", "盈建科提示");
				return;
			}
			if (annotationSymbolType == null && family != null)
			{
				foreach (FamilySymbol familySymbol in family.GetSymbols())
				{
					AnnotationSymbolType annotationSymbolType2 = (AnnotationSymbolType)familySymbol;
					if (annotationSymbolType2 != null)
					{
						annotationSymbolType = annotationSymbolType2;
						break;
					}
				}
			}
			Transaction transaction = new Transaction(this.m_doc, "hy");
			transaction.Start();
			int num = 0;
			bool flag = true;
			IList<Space> list = new List<Space>();
			try
			{
				IList<Element> projectValidRooms = RevitFilter.GetProjectValidRooms(this.m_doc);
				List<LinkedDocumentInfo> linkAllRoom = this.GetLinkAllRoom(this.commData.Application);
				if (projectValidRooms.Count == 0 && linkAllRoom.Count == 0)
				{
					transaction.RollBack();
					MessageBox.Show("当前项目中不存在房间或房间不符合创建条件，请创建。", "盈建科提示");
					base.Close();
					return;
				}
				List<AnnotationSymbol> list2 = new List<AnnotationSymbol>();
				foreach (Element element in RevitFilter.GetElementsOfType(this.m_doc, typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_GenericAnnotation).ToElements())
				{
					AnnotationSymbol annotationSymbol = element as AnnotationSymbol;
					if (annotationSymbol != null && annotationSymbol.Name == "房间照明标记")
					{
						list2.Add(annotationSymbol);
					}
				}
				IEnumerable<Element> enumerable = RevitFilter.GetElementByCategory(this.m_doc, BuiltInCategory.OST_MEPSpaces).ToElements();
				IList<Space> list3 = new List<Space>();
				foreach (Element element2 in enumerable)
				{
					Space space = element2 as Space;
					if (space != null && space.GetBoundarySegments(new SpatialElementBoundaryOptions()).Count > 0)
					{
						list3.Add(space);
					}
				}
				Dictionary<string, string> dictionary = new Dictionary<string, string>();
				foreach (object obj in ((IEnumerable)this.dgvRoomKeyInfo.Rows))
				{
					DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
					string key = dataGridViewRow.Cells["KeyName"].Value.ToString();
					string value = dataGridViewRow.Cells["TypeID"].Value.ToString();
					dictionary.Add(key, value);
				}
				List<Room> list4 = new List<Room>();
				foreach (Element element3 in projectValidRooms)
				{
					Room room = element3 as Room;
					if (room != null && this.IsInSelectedFloor(this.m_doc.GetElementById(room.LevelId) as Level))
					{
						string roomName = room.get_Parameter(BuiltInParameter.ROOM_NAME).AsString();
						string roomTypeId = this.GetRoomTypeId(dictionary, roomName, true);
						if (roomTypeId == "")
						{
							roomTypeId = this.GetRoomTypeId(dictionary, roomName, false);
						}
						if (roomTypeId == "")
						{
							list4.Add(room);
							flag = false;
						}
						else
						{
							ViewPlan roomView = this.GetRoomView(this.m_doc, room);
							if (roomView != null)
							{
								AnnotationSymbol annotationSymbol2 = Common.IsExsitTag(room, list2);
								if (annotationSymbol2 == null)
								{
									LocationPoint locationPoint = room.Location as LocationPoint;
									annotationSymbol2 = RevitVersionFuncs.NewAnnotationSymbol(this.m_doc, locationPoint.Point, annotationSymbolType, roomView);
								}
								num++;
								Space space2 = Common.IsExsitSpace(room, list3);
								if (space2 == null)
								{
									space2 = Common.CreatSpace(this.m_doc, room);
									list.Add(space2);
								}
								this.SetTagParam(this.m_doc, annotationSymbol2, room, space2, roomTypeId, false, null);
							}
						}
					}
				}
				foreach (LinkedDocumentInfo linkedDocumentInfo in linkAllRoom)
				{
					if (linkedDocumentInfo.room != null && this.IsInSelectedFloor(linkedDocumentInfo.linkDoc.GetElementById(linkedDocumentInfo.room.LevelId) as Level))
					{
						string roomName2 = linkedDocumentInfo.room.get_Parameter(BuiltInParameter.ROOM_NAME).AsString();
						string roomTypeId2 = this.GetRoomTypeId(dictionary, roomName2, true);
						if (roomTypeId2 == "")
						{
							roomTypeId2 = this.GetRoomTypeId(dictionary, roomName2, false);
						}
						if (roomTypeId2 == "")
						{
							list4.Add(linkedDocumentInfo.room);
							flag = false;
						}
						else
						{
							XYZ xyz;
							ViewPlan viewPlan;
							this.GetLineRoomView(linkedDocumentInfo.linkDoc, this.m_doc, linkedDocumentInfo.room, linkedDocumentInfo.transform, out xyz, out viewPlan);
							if (viewPlan != null && xyz != null)
							{
								AnnotationSymbol annotationSymbol3 = Common.IsExsitTag(linkedDocumentInfo.room, list2);
								if (annotationSymbol3 == null)
								{
									Location location = linkedDocumentInfo.room.Location;
									annotationSymbol3 = RevitVersionFuncs.NewAnnotationSymbol(this.m_doc, xyz, annotationSymbolType, viewPlan);
								}
								num++;
								Space space3 = Common.IsExsitSpace(linkedDocumentInfo.room, list3);
								if (space3 == null)
								{
									space3 = Common.CreatSpace(linkedDocumentInfo.linkDoc, this.m_doc, linkedDocumentInfo.room, linkedDocumentInfo.transform);
									list.Add(space3);
								}
								this.SetTagParam(this.m_doc, annotationSymbol3, linkedDocumentInfo.room, space3, roomTypeId2, true, linkedDocumentInfo.linkDoc);
							}
						}
					}
				}
				foreach (Space space4 in list)
				{
					this.m_doc.Delete(space4.Id);
				}
				this.xmlInfo.SaveSpaceKeyword(DlgCreateRoomTag.listRoomType);
				string text = "";
				if (num > 0)
				{
					text = "成功创建或修改了" + num + "个\"房间照明标记\"。\n\n";
				}
				if (!flag)
				{
					text += "存在未对应关键字的房间，请建立对应关系。也可点击“导出”按钮导出此类房间信息。";
				}
				if (text != "")
				{
					bool bSigned = num == projectValidRooms.Count;
					if (new DlgExportRoomInfo(text, bSigned).ShowDialog() == DialogResult.OK)
					{
						this.ExportRoomInfo(list4);
					}
				}
				transaction.Commit();
			}
			catch (Exception ex)
			{
				transaction.RollBack();
				MessageBox.Show("创建房间标记失败。\n" + ex.Message, "盈建科提示");
			}
			base.Close();
		}

		private bool IsInSelectedFloor(Level level)
		{
			if (this.m_lstSelLevels.Count <= 0 || level == null)
			{
				return false;
			}
			for (int i = 0; i < this.m_lstSelLevels.Count; i++)
			{
				if (Math.Abs(this.m_lstSelLevels[i].GetParameter(BuiltInParameter.LEVEL_ELEV).AsDouble() - level.GetParameter(BuiltInParameter.LEVEL_ELEV).AsDouble()) < 0.1)
				{
					return true;
				}
			}
			return false;
		}

		private void ExportRoomInfo(List<Room> lstRoom)
		{
			this.saveFileDialog1.Filter = "TXT文件(*.txt)|*.txt";
			this.saveFileDialog1.RestoreDirectory = true;
			this.saveFileDialog1.FileName = "未标记房间信息.txt";
			if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
			{
				string fileName = this.saveFileDialog1.FileName;
				try
				{
					StreamWriter streamWriter = new StreamWriter(fileName, false, Encoding.Default);
					streamWriter.WriteLine("[房间名称]\t[房间编号]\t[楼层]");
					foreach (Room room in lstRoom)
					{
						string text = room.GetParameter(BuiltInParameter.ROOM_NAME).AsString();
						string text2 = room.GetParameter(BuiltInParameter.ROOM_NUMBER).AsString();
						string name = (this.m_doc.GetElementById(room.LevelId) as Level).Name;
						streamWriter.WriteLine(string.Concat(new string[]
						{
							text,
							"\t\t",
							text2,
							"\t\t",
							name
						}));
					}
					streamWriter.Close();
				}
				catch (Exception)
				{
					return;
				}
				MessageBox.Show("数据成功保存到" + this.saveFileDialog1.FileName, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
			}
		}

		private string GetRoomTypeId(Dictionary<string, string> dictagRoomKeyName, string roomName, bool isAll)
		{
			string text = "";
			foreach (KeyValuePair<string, string> keyValuePair in dictagRoomKeyName)
			{
				foreach (string text2 in keyValuePair.Key.Split(new char[]
				{
					',',
					'，'
				}))
				{
					if (isAll)
					{
						if (roomName == text2)
						{
							text = keyValuePair.Value;
							break;
						}
					}
					else
					{
						if (roomName.Contains(text2))
						{
							text = keyValuePair.Value;
							break;
						}
						if (text2.Contains('*') || text2.Contains('?'))
						{
							string pattern = this.WildcardToRegex(text2);
							if (Regex.IsMatch(roomName, pattern))
							{
								text = keyValuePair.Value;
								break;
							}
						}
					}
				}
				if (text != "")
				{
					break;
				}
			}
			return text;
		}

		private string WildcardToRegex(string pattern)
		{
			return "^" + Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".?") + "$";
		}

		private void SetTagParam(Autodesk.Revit.DB.Document doc, AnnotationSymbol annotationSymbol, Room room, Space space, string typeId, bool isLink, Autodesk.Revit.DB.Document documentLin)
		{
			try
			{
				if (isLink)
				{
					ElementId elementId = room.get_Parameter(BuiltInParameter.ROOM_LEVEL_ID).AsElementId();
					Level level = documentLin.GetElementById(elementId) as Level;
					Level level2 = null;
					foreach (Element element in RevitFilter.GetElementsOfType(doc, typeof(Level), BuiltInCategory.OST_Levels).ToElements().ToList<Element>())
					{
						if (Math.Abs((element as Level).Elevation - level.Elevation) < 0.1)
						{
							level2 = (element as Level);
							break;
						}
					}
					annotationSymbol.GetParameter("房间照明标记标高").Set(level2.Id.ToString());
				}
				else
				{
					ElementId elementId2 = room.GetParameter(BuiltInParameter.ROOM_LEVEL_ID).AsElementId();
					annotationSymbol.GetParameter("房间照明标记标高").Set(elementId2.ToString());
				}
				annotationSymbol.GetParameter("房间照明标记ID").Set(annotationSymbol.Id.ToString());
				annotationSymbol.GetParameter("房间ID").Set(room.Id.ToString());
				annotationSymbol.GetParameter("房间计算状态").Set(0);
				string text = room.GetParameter(BuiltInParameter.ROOM_NUMBER).AsString();
				annotationSymbol.GetParameter("房间编号").Set(text);
				string text2 = room.GetParameter(BuiltInParameter.ROOM_NAME).AsString();
				annotationSymbol.GetParameter("房间名称").Set(text2);
				double val = room.GetParameter(BuiltInParameter.ROOM_AREA).AsDouble();
				annotationSymbol.GetParameter("房间面积").Set(Math.Round(AssistFunc.feet2ToM2(val), 2));
				double num = space.get_Parameter(BuiltInParameter.ROOM_UPPER_OFFSET).AsDouble();
				double num2 = space.get_Parameter(BuiltInParameter.ROOM_LOWER_OFFSET).AsDouble();
				double num3 = AssistFunc.feetToMM(num - num2) / 1000.0;
				annotationSymbol.GetParameter("房间高度").Set(num3);
				double num4 = Math.Round(AssistFunc.feetToMM(space.GetParameter(BuiltInParameter.RBS_ELEC_ROOM_LIGHTING_CALC_WORKPLANE).AsDouble()) / 1000.0, 2);
				annotationSymbol.GetParameter("工作面高度").Set(num4);
				annotationSymbol.GetParameter("安装高度").Set(3);
				if (num3 < 3.0)
				{
					annotationSymbol.GetParameter("安装高度").Set(num3);
				}
				if (isLink)
				{
					double roomOpeningData = this.GetRoomOpeningData(documentLin, room);
					annotationSymbol.GetParameter("窗面积").Set(roomOpeningData);
				}
				else
				{
					double roomOpeningData2 = this.GetRoomOpeningData(doc, room);
					annotationSymbol.GetParameter("窗面积").Set(roomOpeningData2);
				}
				annotationSymbol.GetParameter("窗反射系数").Set(20);
				double num5 = space.GetParameter(BuiltInParameter.RBS_ELEC_ROOM_REFLECTIVITY_CEILING).AsDouble() * 100.0;
				annotationSymbol.GetParameter("顶棚反射系数").Set(num5);
				double num6 = space.GetParameter(BuiltInParameter.RBS_ELEC_ROOM_REFLECTIVITY_WALLS).AsDouble() * 100.0;
				annotationSymbol.GetParameter("墙上部反射系数").Set(num6);
				annotationSymbol.GetParameter("墙下部反射系数").Set(num6);
				double num7 = space.GetParameter(BuiltInParameter.RBS_ELEC_ROOM_REFLECTIVITY_FLOOR).AsDouble() * 100.0;
				annotationSymbol.GetParameter("地面反射系数").Set(num7);
				annotationSymbol.GetParameter("房间周长").Set(AssistFunc.feetToMM(room.Perimeter) / 1000.0);
				annotationSymbol.GetParameter("墙周长").Set(AssistFunc.feetToMM(this.GetWallPerimeter(room)) / 1000.0);
				string text3 = "";
				foreach (RoomType roomType in DlgCreateRoomTag.listRoomType)
				{
					if (roomType.TypeID == typeId)
					{
						text3 = roomType.TypeName;
						break;
					}
				}
				string[] array = text3.Split(new char[]
				{
					'-'
				});
				BuildingPlaceData roomTypeDataById = BuildingPlaceDb.ThisDb.GetRoomTypeDataById(array[0], array[1], array[2], typeId);
				if (roomTypeDataById != null)
				{
					annotationSymbol.GetParameter("标准照度").Set(roomTypeDataById.IllStandard);
					annotationSymbol.GetParameter("标准功率密度").Set(Convert.ToDouble(roomTypeDataById.NowPD));
				}
			}
			catch (Exception)
			{
				MessageBox.Show("为\"房间照明标记\"的参数进行赋值时异常。", "盈建科提示");
				throw;
			}
		}

		private double GetRoomOpeningData(Autodesk.Revit.DB.Document m_doc, Room room)
		{
			Level level = m_doc.GetElementById(room.LevelId) as Level;
			double num = 0.0;
			List<ElementId> list = new List<ElementId>();
			if (room.GetBoundarySegments(new SpatialElementBoundaryOptions()) == null)
			{
				return 0.0;
			}
			foreach (IList<BoundarySegment> list2 in room.GetBoundarySegments(new SpatialElementBoundaryOptions()))
			{
				foreach (BoundarySegment segment in list2)
				{
					Wall wall = segment.GetElement(m_doc) as Wall;
					if (wall != null && !list.Contains(wall.Id))
					{
						list.Add(wall.Id);
						if (wall != null)
						{
							IList<FamilyInstance> wallAssoDoorWins = WallAssistFunc.GetWallAssoDoorWins(m_doc, wall, BuiltInCategory.OST_Windows, level);
							if (wallAssoDoorWins != null)
							{
								foreach (FamilyInstance familyInstance in wallAssoDoorWins)
								{
									LocationPoint locationPoint = familyInstance.Location as LocationPoint;
									XYZ offsetDoorWinPosition = this.GetOffsetDoorWinPosition(m_doc, wall, locationPoint.Point, 1);
									XYZ offsetDoorWinPosition2 = this.GetOffsetDoorWinPosition(m_doc, wall, locationPoint.Point, -1);
									if (room.IsPointInRoom(offsetDoorWinPosition) || room.IsPointInRoom(offsetDoorWinPosition2))
									{
										FamilySymbol symbol = familyInstance.Symbol;
										if (symbol != null)
										{
											double num2 = AssistFunc.feetToMM(symbol.get_Parameter(BuiltInParameter.FAMILY_HEIGHT_PARAM).AsDouble()) / 1000.0;
											double num3 = AssistFunc.feetToMM(symbol.get_Parameter(BuiltInParameter.CASEWORK_WIDTH).AsDouble()) / 1000.0;
											double num4 = num2 * num3;
											num += num4;
										}
									}
								}
							}
						}
					}
				}
			}
			return Math.Round(num, 2);
		}

		private XYZ GetOffsetDoorWinPosition(Autodesk.Revit.DB.Document m_doc, Wall wall, XYZ OriPos, int dir)
		{
			XYZ result = new XYZ();
			if (WallAssistFunc.GetWallCurveType(wall) == WallCurveType.eLineWall)
			{
				XYZ startPt = WallAssistFunc.GetStartPt(wall);
				XYZ xyz = (WallAssistFunc.GetEndPt(wall) - startPt).Normalize();
				xyz = RevitVersionFuncs.CreateRotationAtPoint(XYZ.BasisZ, Math.PI*.5, XYZ.Zero).OfVector(xyz);
				result = OriPos + xyz * (double)dir * AssistFunc.mmToFeet(WallAssistFunc.GetWallThick(m_doc, wall) * 1.5);
			}
			else if (WallAssistFunc.GetWallCurveType(wall) == WallCurveType.eArcWall)
			{
				Arc arc = (wall.Location as LocationCurve).Curve as Arc;
				if (arc == null)
				{
					return null;
				}
				XYZ center = arc.Center;
				XYZ xyz2 = (OriPos - center).Normalize();
				result = OriPos + xyz2 * (double)dir * AssistFunc.mmToFeet(WallAssistFunc.GetWallThick(m_doc, wall) * 1.5);
			}
			return result;
		}

		private double GetWallPerimeter(Room room)
		{
			double num = 0.0;
			List<ElementId> list = new List<ElementId>();
			if (room.GetBoundarySegments(new SpatialElementBoundaryOptions()) == null)
			{
				return num;
			}
			foreach (IList<BoundarySegment> list2 in room.GetBoundarySegments(new SpatialElementBoundaryOptions()))
			{
				foreach (BoundarySegment segment in ((List<BoundarySegment>)list2))
				{
					Wall wall = segment.GetElement(this.m_doc) as Wall;
					if (wall != null && !list.Contains(wall.Id))
					{
						list.Add(wall.Id);
						num += segment.GetCurve().Length;
					}
				}
			}
			return num;
		}

		public ViewPlan GetRoomView(Autodesk.Revit.DB.Document doc, Room compareRoom)
		{
			Level level = doc.GetElementById(compareRoom.LevelId) as Level;
			List<ViewPlan> list = new List<ViewPlan>();
			foreach (ViewPlan viewPlan in (from v in RevitFilter.GetElementsOfType(doc, typeof(ViewPlan)).ToElements()
			select v as ViewPlan).ToList<ViewPlan>())
			{
				if ((int)viewPlan.ViewType == 1 && !viewPlan.IsTemplate && viewPlan.get_Parameter(BuiltInParameter.VIEW_DISCIPLINE).AsInteger() == 8)
				{
					list.Add(viewPlan);
					if (viewPlan.GetParameter("子规程") != null && viewPlan.GetParameter("子规程").AsString() == "照明" && viewPlan.GenLevel.Id == level.Id)
					{
						return viewPlan;
					}
				}
			}
			foreach (ViewPlan viewPlan2 in list)
			{
				if (viewPlan2.GenLevel.Id == level.Id)
				{
					return viewPlan2;
				}
			}
			return null;
		}

		public void GetLineRoomView(Autodesk.Revit.DB.Document documentLin, Autodesk.Revit.DB.Document doc, Room room, Transform transform, out XYZ tranPoint, out ViewPlan viewPlan)
		{
			Level level = documentLin.GetElementById(room.LevelId) as Level;
			XYZ point = (room.Location as LocationPoint).Point;
			tranPoint = this.TransformPoint(point, transform);
			new List<double>();
			Level level2 = null;
			foreach (Element element in RevitFilter.GetElementsOfType(doc, typeof(Level), BuiltInCategory.OST_Levels).ToElements().ToList<Element>())
			{
				if (Math.Abs((element as Level).Elevation - level.Elevation) < 0.1)
				{
					level2 = (element as Level);
					break;
				}
			}
			if (level2 == null)
			{
				throw new Exception("当前项目中未创建链接房间所需要的标高");
			}
			List<ViewPlan> list = new List<ViewPlan>();
			foreach (ViewPlan viewPlan2 in (from v in RevitFilter.GetElementsOfType(doc, typeof(ViewPlan)).ToElements()
			select v as ViewPlan).ToList<ViewPlan>())
			{
				if ((int)viewPlan2.ViewType == 1 && !viewPlan2.IsTemplate && viewPlan2.get_Parameter(BuiltInParameter.VIEW_DISCIPLINE).AsInteger() == 8)
				{
					list.Add(viewPlan2);
					if (viewPlan2.GetParameter("子规程") != null && viewPlan2.GetParameter("子规程").AsString() == "照明" && Math.Abs(viewPlan2.GenLevel.Elevation - level2.Elevation) < 0.1)
					{
						viewPlan = viewPlan2;
						return;
					}
				}
			}
			foreach (ViewPlan viewPlan3 in list)
			{
				if (Math.Abs(viewPlan3.GenLevel.Elevation - level2.Elevation) < 0.1)
				{
					viewPlan = viewPlan3;
					return;
				}
			}
			viewPlan = null;
		}

		private double FindProximal(List<double> arrays, double target)
		{
			double result = 0.0;
			double num = Math.Abs(target - arrays[0]);
			foreach (double num2 in arrays)
			{
				double num3 = Math.Abs(target - num2);
				if (num3 < num)
				{
					num = num3;
					result = num2;
				}
				else if (num3 == num)
				{
					result = num2;
				}
			}
			return result;
		}

		public XYZ TransformPoint(XYZ point, Transform transform)
		{
			double x = point.X;
			double y = point.Y;
			double z = point.Z;
			XYZ xyz = transform.get_Basis(0);
			XYZ xyz2 = transform.get_Basis(1);
			XYZ xyz3 = transform.get_Basis(2);
			XYZ origin = transform.Origin;
			double num = x * xyz.X + y * xyz2.X + z * xyz3.X + origin.X;
			double num2 = x * xyz.Y + y * xyz2.Y + z * xyz3.Y + origin.Y;
			double num3 = x * xyz.Z + y * xyz2.Z + z * xyz3.Z + origin.Z;
			return new XYZ(num, num2, num3);
		}

		public List<LinkedDocumentInfo> GetLinkAllRoom(UIApplication uiApp)
		{
			List<LinkedDocumentInfo> list = new List<LinkedDocumentInfo>();
			Document document = uiApp.ActiveUIDocument.Document;
			foreach (Element element in RevitFilter.GetElementsOfType(document, typeof(Instance), BuiltInCategory.OST_RvtLinks))
			{
				Instance instance = element as Instance;
				if (instance != null)
				{
					Transform totalTransform = instance.GetTotalTransform();
					(document.GetElement(instance.GetTypeId()) as RevitLinkType).get_Parameter(BuiltInParameter.WALL_ATTR_ROOM_BOUNDING).Set(1);
					if (instance is RevitLinkInstance)
					{
						Document linkDocument = (instance as RevitLinkInstance).GetLinkDocument();
						foreach (Element element2 in RevitFilter.GetProjectValidRooms(linkDocument))
						{
							LinkedDocumentInfo linkedDocumentInfo = new LinkedDocumentInfo();
							Room room = element2 as Room;
							if (room.Location != null)
							{
								linkedDocumentInfo.room = room;
								linkedDocumentInfo.transform = totalTransform;
								linkedDocumentInfo.linkDoc = linkDocument;
								list.Add(linkedDocumentInfo);
							}
						}
					}
				}
			}
			return list;
		}

		private void btnFloors_Click(object sender, EventArgs e)
		{
			DlgBuildingFloors dlgBuildingFloors = new DlgBuildingFloors(this.m_doc, this.m_lstSelLevels);
			if (DialogResult.OK == dlgBuildingFloors.ShowDialog())
			{
				this.m_lstSelLevels.Clear();
				this.m_lstSelLevels = dlgBuildingFloors.m_lstSelLevels;
			}
		}

		private XmlInfo xmlInfo;

		private static List<RoomType> listRoomType;

		private ExternalCommandData commData;

		private Document m_doc;

		private List<Level> m_lstSelLevels;
	}
}
